package com.ikaros.service.admin.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ikaros.dao.SysMenuMapper;
import com.ikaros.dao.SysRoleMenuMapper;
import com.ikaros.dao.SysUserMapper;
import com.ikaros.emnus.MenuEnum;
import com.ikaros.model.entity.SysMenu;
import com.ikaros.model.entity.SysUser;
import com.ikaros.model.query.BaseQuery;
import com.ikaros.service.admin.SysMenuService;
import com.ikaros.service.admin.SysUserService;
import com.ikaros.utils.Constant;
import com.ikaros.utils.EhcacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Ikaros on 2017/9/29.
 */
@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper,SysMenu> implements SysMenuService{
    @Autowired
    private SysUserService sysUserService;
    @Resource
    private EhcacheUtil ehcacheUtil;
    @Override
    public List<SysMenu> queryList(Map<String, Object> map) {
        return baseMapper.queryList(map);
    }

    @Override
    public List<SysMenu> getUserMenuList(Long userId) {
        String cacheName = EhcacheUtil.menuCacheName + userId;
        Object object = ehcacheUtil.get(EhcacheUtil.ADMINMENUEHCACHENAME, cacheName);
        if (null != object) {
            if (object instanceof List) {
                log.info("用户菜单列表从EhCache缓存拿值");
                return (List<SysMenu>) object;
            }
        }
        // 系统管理员，拥有最高权限
        if (userId.equals(Constant.AdminId)) {
            List<SysMenu> allMenuList = this.getAllMenuList(null);
            ehcacheUtil.put(EhcacheUtil.ADMINMENUEHCACHENAME, cacheName, allMenuList);
            log.info("admin创建缓存");
            return allMenuList;
        }

        // 用户菜单列表(ID)
        List<Long> userMenuIdList = sysUserService.getUserMenuIdList(userId);
        //获取所有菜单列表 递归
        List<SysMenu> allMenuList = this.getAllMenuList(userMenuIdList);
        ehcacheUtil.put(EhcacheUtil.ADMINMENUEHCACHENAME, cacheName, allMenuList);
        log.info("非admin创建缓存");
        return allMenuList;
    }

    /**
     * 获取所有菜单列表
     */
    private List<SysMenu> getAllMenuList(List<Long> userMenuIdList) {
        // 查询根菜单列表
        List<SysMenu> menuList = this.queryListByParentId(0L, userMenuIdList);
        // 递归获取子菜单
        //[SysMenu(menuId=1, parentId=0, name=系统管理, url=, perms=, type=0, icon=fa fa-cog, orderNum=0, open=null, list=null)]
        this.getMenuTreeList(menuList, userMenuIdList);
        //[SysMenu(menuId=1, parentId=0, name=系统管理, url=, perms=, type=0, icon=fa fa-cog, orderNum=0, open=null, list=[SysMenu(menuId=2, parentId=1, name=管理员列表, url=admin/sys/admin.html, perms=, type=1, icon=fa fa-user, orderNum=1, open=null, list=null), SysMenu(menuId=3, parentId=1, name=角色管理, url=admin/sys/role.html, perms=null, type=1, icon=fa fa-user-secret, orderNum=2, open=null, list=null), SysMenu(menuId=4, parentId=1, name=菜单管理, url=admin/sys/menu.html, perms=null, type=1, icon=fa fa-th-list, orderNum=3, open=null, list=null), SysMenu(menuId=17, parentId=1, name=监控管理, url=druid/index.html, perms=druid:druid:manager, type=1, icon=fa fa-cogs, orderNum=3, open=null, list=null), SysMenu(menuId=18, parentId=1, name=Swagger管理, url=swagger-ui.html, perms=swaggerui:swaggerui:manager, type=1, icon=fa fa-diamond, orderNum=4, open=null, list=null)])]
        return menuList;
    }

    /**
     * 根据父菜单id查询menu
     * @param parentId 父菜单ID
     * @param userMenuIdList
     * @return
     */
    public List<SysMenu> queryListByParentId(Long parentId, List<Long> userMenuIdList) {
        List<SysMenu> menuList = baseMapper.queryListByParentId(parentId);
        if (userMenuIdList == null) {
            return menuList;
        }
        List<SysMenu> userMenuList = new ArrayList<>();
        for (SysMenu menu : menuList) {
            //如果用户菜单id列表包含 （根据父菜单，查询子菜单）的子菜单id
            if (userMenuIdList.contains(menu.getMenuId())) {
                userMenuList.add(menu);
            }
        }
       /* System.out.println(userMenuList);*/
        return userMenuList;
    }

    /**
     * 递归
     * @param menuList 查询根菜单列表
     * @param userMenuIdList
     * @return
     * 如果是目录 查询菜单（父id是1（跟id）） 然后set在sysmenu list里面
     */
    private List<SysMenu> getMenuTreeList(List<SysMenu> menuList, List<Long> userMenuIdList) {
        List<SysMenu> subMenuList = new ArrayList<SysMenu>();

        for (SysMenu entity : menuList) {
            //Integer比较最好是用equals 别用== findbug会报bug
            if (entity.getType().equals(MenuEnum.CATALOG.getCode())) {// 目录
                //setList里面放的菜单列表  //目录父id为0 子id为1  然后以1为父id 查询子id 查询出了菜单列
                entity.setList(getMenuTreeList(queryListByParentId(entity.getMenuId(), userMenuIdList), userMenuIdList));
            }
            subMenuList.add(entity);
        }
        return subMenuList;
    }
}
